<template>
  <div class="weather-card" v-if="regionWeatherRef.temp">
    <div class="weather-info">
      <div class="weather-top">
        <div class="temp-box">
          <div class="img-box">
            <img class="weather-icon" :src="iconRef" />
            {{ regionWeatherRef.weather }}
            <span class="level" v-if="regionWeatherRef.aqiLevel">
              <img
                :class="`level-icon ${
                  regionWeatherRef.aqiLevel === 1
                    ? 'excellent'
                    : regionWeatherRef.aqiLevel === 2
                    ? 'good'
                    : 'bad'
                }`"
                :src="levelIcon"
              />
              {{ regionWeatherRef.aqiDesc }}
              {{ regionWeatherRef.aqiValue }}
            </span>
          </div>
          <div class="temp">{{ regionWeatherRef.temp }}°</div>
        </div>
        <div class="rest">
          {{ regionWeatherRef.windDir }}:{{ regionWeatherRef.windLevel + '级' }}
        </div>
      </div>

      <ul class="region-bottom">
        <li>
          <img src="../../assets/imgs/richuriluo.png" />
          <div class="cont-item">
            <p>
              日出{{ regionWeatherRef.sunRise }} 日落{{
                regionWeatherRef.sunDown
              }}
            </p>
          </div>
        </li>
        <li>
          <img src="../../assets/imgs/wendu.png" />
          <div class="cont-item">
            <p>
              最低{{ regionWeatherRef.tempLow }}° 最高{{
                regionWeatherRef.tempHigh
              }}°
            </p>
          </div>
        </li>
        <li>
          <img src="../../assets/imgs/shidu.png" />
          <div class="cont-item">
            <p>湿度{{ regionWeatherRef.humidity + '%' }}</p>
          </div>
        </li>
      </ul>
    </div>
    <div class="weather-right" v-if="detailRef && detailRef.length">
      <div class="live-box">
        <h6>
          今日生活指数
          <span>
            <SearchCity @onSelectedCity="onSelectedCity">
              <template #cont>
                <span
                  >{{ regionWeatherRef.province }}-{{
                    regionWeatherRef.city
                  }}&nbsp; <el-icon> <Location /> </el-icon
                ></span>
              </template>
            </SearchCity>
          </span>
        </h6>
        <ul>
          <li v-for="(item, index) in detailRef" :key="index">
            <img :src="item.icon" />
            <p>{{ item.indexLevelDesc }}</p>
            <span>{{ item.indexType }}</span>
          </li>
        </ul>
      </div>
    </div>
    <div class="future-weather" @click="openFutureWeather">
      未来15天预报<el-icon>
        <CaretRight />
      </el-icon>
    </div>
  </div>
  <WeatherSkeletion v-else />
</template>
<script setup name="WeatherCard">
import {
  onMounted,
  onUnmounted,
  onActivated,
  ref,
  watch,
  inject,
  nextTick,
} from 'vue';
import { useRouter } from 'vue-router';
import { Location, CaretRight } from '@element-plus/icons-vue';
import moment from 'moment';
import useSymbols from '../../compostions/useSymbols.js';
import {
  getSearchCityApi,
  getWeatherByCityIdApi,
  getIndexDetailApi,
  getProApi,
} from '../../apis/weatherApi.js';
import { iconArr, levelIcon } from '../../util/baseIcon.js';
import hexToRgb from '../../util/hexToRgb.js';
import SearchCity from './SearchCity.vue';
import WeatherSkeletion from './WeatherSkeleton.vue';

const { systemColorReadonly } = inject(useSymbols);

const router = useRouter();

const cityIdRef = ref();
const iconRef = ref('');
const detailRef = ref([]);
const regionWeatherRef = ref({
  province: '', // 省、直辖市
  city: '', // 定位地区
  date: '', // 日期星期
  humidity: '', // 湿度
  windLevel: '', // 风速（当前）
  windLevelDay: '', // 风速（白天）
  windLevelNight: '', // 风速（晚上）
  windDir: '', // 方向（当前）
  windDirDay: '', // 风向（白天）
  windDirNight: '', // 风向（晚上）
  temp: '', // 温度 (当前)
  tempHigh: '', // 温度（最高）
  tempLow: '', // 温度（最低）
  weather: '', // 天气（当前）
  weatherDay: '', // 天气（白天）
  weatherNight: '', // 天气（晚上）
  sunRise: '', // 日出
  sunDown: '', // 日落
  aqiDesc: '',
  aqiLevel: '',
  aqiValue: '',
});

// 打开15天预报
const openFutureWeather = () => {
  const platform = window?.myApi?.platform
    ? `&platform=${window.myApi.platform}`
    : '';
  const newUrl = router.resolve({ path: '/weather' });
  const { province, city, cityname } = regionWeatherRef.value;
  const paramStr = `province=${province}&city=${city}`;
  const { origin, pathname } = window.location;
  const url = `${origin}${pathname}${newUrl.href}?cityId=${cityIdRef.value}&${paramStr}${platform}`;
  if (window.myApi) {
    window.myApi.sendOpenView(url);
  } else {
    window.open(url);
  }
};

// 手动选择区域
const onSelectedCity = ({ cityId, city, localPname }) => {
  cityIdRef.value = cityId;
  regionWeatherRef.value.city = city;
  regionWeatherRef.value.province = localPname;
  getWeatherInfo();
};

// 获取当前定位区域的天气
const getWeatherInfo = async () => {
  const { data } = await getWeatherByCityIdApi(cityIdRef.value);
  const { forecastDays, condition } = data;
  // 创建一个新的Date对象，默认为当前日期和时间
  const timestamp = Math.floor(new Date().setHours(0, 0, 0, 0) / 1000);
  const nowDateData = forecastDays.forecastDay.find(
    (item) => item.predictDate === timestamp
  );
  regionWeatherRef.value = {
    ...regionWeatherRef.value,
    ...nowDateData,
    ...condition,
  };
  regionWeatherRef.value.sunRise = moment(nowDateData.sunRise * 1000).format(
    'HH:mm'
  );
  regionWeatherRef.value.sunDown = moment(nowDateData.sunDown * 1000).format(
    'HH:mm'
  );

  // 天气图标
  const src = await import(`../../assets/imgs/weather/W${condition.icon}.png`);
  iconRef.value = src.default;
};

const getDetail = async (cityId) => {
  const { data } = await getIndexDetailApi(cityId);
  const list = data.indexs;
  detailRef.value = list.map((item) => {
    const res = iconArr.find((el) => item.indexType === el.prop);
    item.icon = res.icon;
    return item;
  });
};

// 获取ip
// function getUserIP(callback) {
//   return new Promise((resolve, reject) => {
//     fetch('https://api.vore.top/api/IPdata')
//       .then((response) => response.json())
//       .then((json) => {
//         console.log(json)
//         resolve(json.ip);
//       });
//   });
// }

const getRegion = async (ip) => {
  let province, city;
  if (window.myApi) {
    const res = await window.myApi.sendIPQueryRegion(ip);
    const { pro, city:wCity } = res ? JSON.parse(res) : {};
    province = pro;
    city = wCity;
  } else {
    const {
      data: { regionName, city:aCity },
    } = await getProApi();
    province = regionName;
    city = aCity;
  }
  regionWeatherRef.value.province = province;
  regionWeatherRef.value.city = city;
  return city;
};

// 五分钟定时调用接口获取最新天气
let timerRef = ref(null);
const startTimer = () => {
  timerRef.value = setInterval(() => {
    getWeatherInfo();
  }, 1000 * 60 * 5);
};
const stopTimer = () => {
  if (timerRef.value) {
    clearInterval(timerRef.value);
    timerRef.value = null;
  }
};
onActivated(() => {
  setCardStyleProperty(hexToRgb(systemColorReadonly.value.color));
});
onMounted(async () => {
  // const ip = window.myApi && (await getUserIP());
  const cityname = await getRegion();
  const { data } = await getSearchCityApi(cityname);
  const cityId = data.city_list[0].cityId;
  cityIdRef.value = cityId;
  await getDetail(cityId);
  await getWeatherInfo();
  startTimer();
});
onUnmounted(() => {
  stopTimer();
});

const setCardStyleProperty = (colors) => {
  const weatherCard = document.querySelector('.weather-card');
  if (!weatherCard) return;
  const [r, g, b] = colors;
  weatherCard.style.setProperty('--bg-color-top', `rgba(${r},${g},${b},0.5)`);
  weatherCard.style.setProperty(
    '--bg-after-color',
    `rgba(${r},${g},${b},0.09)`
  );
  weatherCard.style.setProperty(
    '--bg-before-color',
    `rgba(${r},${g},${b},0.1)`
  );
  weatherCard.style.setProperty(
    '--bg-color-bottom',
    `rgba(${r},${g},${b},0.8)`
  );
};

watch(
  [() => systemColorReadonly.value.color, () => regionWeatherRef.value],
  ([newColor, newWeather]) => {
    if (newWeather.temp) {
      nextTick().then(() => {
        setCardStyleProperty(hexToRgb(systemColorReadonly.value.color));
      });
    }
  },
  {
    deep: true,
    immediate: true,
  }
);
</script>
<style scoped lang="less">
.weather-card {
  --font-color: #ffffff;
  --card-border-radius: 18px;
  --bg-after-color: rgba(87, 104, 230, 0.09);
  --bg-before-color: rgba(87, 104, 230, 0.1);
  --bg-color-top: rgba(87, 104, 230, 0.5);
  --bg-color-bottom: rgba(87, 104, 230, 0.8);
  border-radius: var(--card-border-radius);
  width: 100%;
  height: 319px;
  background: linear-gradient(
    to bottom,
    var(--bg-color-top),
    var(--bg-color-bottom)
  );
  overflow: hidden;
  position: relative;

  &:after {
    position: absolute;
    bottom: -70px;
    left: 0;
    z-index: 0;
    width: 300px;
    height: 300px;
    border-radius: 50%;
    background-color: var(--bg-after-color);
    content: '';
    animation: ballAnimation1 8s infinite;
  }

  &:before {
    position: absolute;
    bottom: -120px;
    left: 140px;
    z-index: 1;
    width: 500px;
    height: 500px;
    border-radius: 50%;
    background-color: var(--bg-before-color);
    content: '';
    animation: ballAnimation1 8s 4s infinite;
  }

  .weather-info {
    color: var(--font-color);
    position: relative;
    height: 100%;

    .weather-top {
      position: absolute;
      top: 30px;
      left: 20px;
      z-index: 2;

      .temp-box {
        .img-box {
          font-size: 18px;
          display: flex;
          align-items: end;
          line-height: 32px;

          .weather-icon {
            width: 32px;
            margin-inline-end: 8px;
          }

          .level {
            border-radius: 999px;
            display: flex;
            align-items: center;
            font-size: 14px;
            color: #fff;
            background-color: rgba(255, 255, 255, 0.18);
            padding: 0 8px;
            margin-left: 12px;

            .level-icon {
              width: 22px;
              height: 22px;
              border-radius: 50%;
              margin-inline-end: 6px;
            }

            .excellent {
              background: rgb(106, 212, 159);
            }

            .good {
              background: rgb(255, 195, 0);
            }

            .bad {
              background: rgb(248, 68, 3);
            }
          }
        }

        .temp {
          font-size: 92px;
          font-weight: 400;
        }
      }

      .rest {
        font-size: 15px;
        margin-top: 4px;
        opacity: 0.9;
      }
    }

    .region-bottom {
      width: 88%;
      position: absolute;
      left: 20px;
      bottom: 20px;
      z-index: 2;
      display: grid;
      grid-template-columns: repeat(3, 1fr);
      margin: 0;
      padding: 0;

      li {
        display: grid;
        grid-template-columns: 34px 1fr;
        align-items: center;

        img {
          width: 17px;
          height: 17px;
          display: block;
          border-radius: 50%;
          background-color: rgba(255, 255, 255, 0.16);
          padding: 4px;
        }

        .cont-item {
          display: flex;
          font-size: 14px;

          p {
            color: #fff;
            margin: 0;
          }
        }
      }
    }
  }

  .weather-right {
    width: 100%;
    height: 100%;
    position: absolute;
    width: 62%;
    top: 0;
    right: 0;
    z-index: 9;

    .live-box {
      background-color: rgba(255, 255, 255, 0.6);
      // backdrop-filter: blur(5px);
      // border: 1px solid rgba(255, 255, 255, 0.25);
      width: 95%;
      padding: 12px 16px;
      box-sizing: border-box;
      border-radius: 30px;
      margin-top: 20px;

      h6 {
        font-size: 16px;
        font-weight: 500;
        // color: #fff;
        color: #555;
        margin: 0;
        padding: 6px 10px 16px 10px;
        display: flex;
        align-items: end;
        justify-content: space-between;

        span {
          font-size: 12px;
          // color: #efefef;
          color: #888;
          font-weight: normal;
          display: flex;
          align-items: center;
        }
      }

      ul {
        margin: 0;
        padding: 0;
        width: 100%;
        display: grid;
        grid-template-columns: repeat(6, 1fr);
        grid-column-gap: 8px;
        grid-row-gap: 6px;

        li {
          width: 100%;
          text-align: center;

          img {
            width: 20px;
            height: 20px;
          }

          p {
            margin: 0;
            padding: 0;
            font-size: 11px;
            // color: #fff;
            color: #555;
          }

          span {
            display: block;
            font-size: 11px;
            // color: #eee;
            color: #999;
          }
        }
      }
    }
  }

  .future-weather {
    position: absolute;
    right: 18px;
    bottom: 13px;
    z-index: 10;
    font-size: 11px;
    padding: 10px 12px;
    border-radius: 999px;
    background-color: rgba(0, 0, 0, 0.3);
    color: #fff;
    display: flex;
    align-items: center;
    cursor: pointer;

    &:hover {
      font-weight: bold;
      background-color: rgba(0, 0, 0, 0.25);
    }
  }
}
@keyframes ballAnimation1 {
  0% {
    transform: translate(0, 0);
  }
  50% {
    transform: scale(1.2);
  }
  100% {
    transform: translate(0, 0);
  }
}
@keyframes ballAnimation2 {
  0% {
    transform: translate(0, 0) scale(1);
  }
  50% {
    transform: translate(50px, -30px) scale(1.2);
  }
  100% {
    transform: translate(0, 0) scale(1);
  }
}
</style>
